package com.zhilianbao.leyaogo.ui.fragment.me.myaccount;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bql.recyclerview.swipe.SwipeMenuAdapter;
import com.bql.recyclerview.swipe.SwipeMenuCreator;
import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.bql.utils.SystemBarUtils;
import com.bql.utils.ThreadPool;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.alipay.AliPayUtil;
import com.zhilianbao.leyaogo.alipay.IPayCallBack;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.constants.HttpConfig;
import com.zhilianbao.leyaogo.constants.PayConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.api.AddressApi;
import com.zhilianbao.leyaogo.http.api.OrderApi;
import com.zhilianbao.leyaogo.http.api.PayApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.callback.JsonCallback;
import com.zhilianbao.leyaogo.http.callback.LoadingViewCallback;
import com.zhilianbao.leyaogo.model.response.UserLoginInfo;
import com.zhilianbao.leyaogo.model.response.address.Address;
import com.zhilianbao.leyaogo.model.response.me.BalanceResponse;
import com.zhilianbao.leyaogo.model.response.me.RechargeResponse;
import com.zhilianbao.leyaogo.model.response.shoppingcart.Express;
import com.zhilianbao.leyaogo.model.response.shoppingcart.MyBalance;
import com.zhilianbao.leyaogo.model.response.shoppingcart.WXPay;
import com.zhilianbao.leyaogo.ui.activity.me.setting.SetPwdActivity;
import com.zhilianbao.leyaogo.ui.adapter.me.BalanceAdapter;
import com.zhilianbao.leyaogo.ui.fragment.address.ReceiveAddressFragment;
import com.zhilianbao.leyaogo.ui.fragment.base.SwipeRefreshAndLoadFragment;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.WXPayUtils;
import com.zhilianbao.leyaogo.utils.XTipsDialog;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.dialog.CommonDialog;
import com.zhilianbao.leyaogo.view.widgets.MoneyTextView;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by liu on 2016/10/25.
 * 余额fragment
 */
public class BalanceFragment extends SwipeRefreshAndLoadFragment<BalanceResponse> implements View.OnClickListener {
    BalanceAdapter mBalanceAdapter;
    BalanceResponse balanceResponse;
    @BindView(R.id.ll_balance)
    LinearLayout llBalance;
    @BindView(R.id.balance_back)
    ImageView balanceBack;
    @BindView(R.id.balance_history)
    TextView balanceHistory;
    @BindView(R.id.balance)
    MoneyTextView mBalance;
    @BindView(R.id.add_money_now)
    TextView mAddMoneyNow;
    private List<BalanceResponse> mBalanceResponses;
    private int mPayType;//支付方式
    //    private IWXAPI wxApi;
    //    private TextView mTvPayType;
    private int isCheckedPosition = 0;//默认选中第一个为0,不选为-1
    private long mSupplierId;
    private UserLoginInfo mUserLoginInfo;
    private LinearLayout mLlSelectReceiveAddress;
    private ImageView mWxPay;
    private ImageView mAliPay;
    private LinearLayout mLlAdName;
    private LinearLayout mLlNotSetAdName;
    private TextView mTvAdName;
    private TextView mTvAdPhoneNum;
    private TextView mTvStrAddress;
    private AlertDialog mAd;
    private ImageView mIvDismiss;
    private TextView mTvPayNow;
    private BalanceResponse mBalanceResponse;

    public static BalanceFragment getInstance() {
        BalanceFragment fragment = new BalanceFragment();
        return fragment;
    }

    @Override
    public void onRcvItemClick(RecyclerView.ViewHolder holder, int position) {
        for (int i = 0; i < mBalanceResponses.size(); i++) {
            balanceResponse = mBalanceResponses.get(i);
            if (i != position) {
                balanceResponse.setIsCheck(false);
                balanceResponse.setIsCheckPosition(-1);
                isCheckedPosition = -1;
            }
        }
        balanceResponse = mBalanceResponses.get(position);
        if (!balanceResponse.getIsCheck()) {
            isCheckedPosition = position;
            balanceResponse.setIsCheckPosition(position);
        } else {
            isCheckedPosition = -1;
            balanceResponse.setIsCheckPosition(-1);
        }
        balanceResponse.setIsCheck(!balanceResponse.getIsCheck());
        mBalanceAdapter.notifyDataSetChanged();
    }

    @Override
    public SwipeMenuAdapter getAdapter() {
        return mBalanceAdapter;
    }

    @Override
    public RecyclerView.ItemDecoration getItemDecoration() {
        return null;
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new GridLayoutManager(mActivity, 2);
    }

    @Override
    public SwipeMenuCreator getSwipeMenuCreator() {
        return null;
    }

    @Override
    public void onLeftSwipeMenuClick(int adapterPosition, int menuPosition) {

    }

    @Override
    public void onRightSwipeMenuClick(int adapterPosition, int menuPosition) {

    }

    @Override
    public boolean canRefresh() {
        return false;
    }

    @Override
    public void onRefresh() {
        loadDataList(1, true);
    }

    @Override
    public void loadDataList(int curPage, boolean isPullToRefresh) {
        mCurPage = curPage;
        loadAvailableBalance();
        loadRechargeGoodsList(isPullToRefresh);
    }

    private void loadRechargeGoodsList(boolean isPullToRefresh) {
        AccountApi.getRechargeGoodsList(mActivity, mSupplierId, mCurPage, pageSize, new RefreshAndLoadCallback<List<BalanceResponse>>(isPullToRefresh) {
            @Override
            public void errorLeftOrEmptyBtnClick(View v) {
                loadDataList(1, true);
            }

            @Override
            public void onResultSuccess(List<BalanceResponse> balanceResponses, @Nullable Response response, LoadingViewCallback callback) {
                mBalanceResponses = balanceResponses;
                handleRefreshAndLoadListData(mCurPage, callback, balanceResponses);
            }

        });
    }

    private void loadAvailableBalance() {
        PayApi.getMyBalance(mActivity, mSupplierId, mUserLoginInfo.getUserId(), new JsonCallback<MyBalance>(mActivity) {
            @Override
            public void onSuccess(MyBalance balance, Call call, Response response) {
                initAvailableBalance(balance);
            }
        });
    }

    private void initAvailableBalance(MyBalance balance) {
        mBalance.setAmount(balance.getAvailableBalance());
    }


    @Override
    public void onLoadMore() {
        loadDataList(mCurPage, true);
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        mBalanceAdapter = new BalanceAdapter(mActivity, mList);
        //        wxApi = WXAPIFactory.createWXAPI(mActivity, PayConfig.WX_APP_ID, true);
        //        wxApi.registerApp(PayConfig.WX_APP_ID);
        initTogetherData();
        getDefautAddress();
    }

    private void initTogetherData() {
        mUserLoginInfo = Utils.getUserLoginInfo();
        mSupplierId = Utils.getSupplierId();

    }

    //获取默认收货地址
    private void getDefautAddress() {
        Address defaultAddress = Utils.getDefaultAddress();
        if (defaultAddress == null) {
            //网络请求默认地址
            //            AddressApi.getAddress(mActivity, mUserLoginInfo.getUserId(), mSupplierId, 1, new DialogCallback<List<Address>>(mActivity) {
            //
            //                @Override
            //                public void onSuccess(List<Address> addresses, Call call, Response response) {
            //                    if (addresses != null && addresses.size() != 0) {
            //                        Address address = addresses.get(0);
            //                        Utils.putDefaultAddress(address);
            //                    }
            //                }
            //            });

            AddressApi.getAddress(mActivity, mUserLoginInfo.getUserId(), mSupplierId, 1, new JsonCallback<List<Address>>(mActivity) {

                @Override
                public void onSuccess(List<Address> addresses, Call call, Response response) {
                    if (addresses != null && addresses.size() != 0) {
                        Address address = addresses.get(0);
                        Utils.putDefaultAddress(address);
                    }
                }
            });
        }
    }


    @Override
    protected void initToolbarHere() {
        SystemBarUtils.immersiveStatusBar(mActivity, 0);
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_balance;
    }

    @OnClick({R.id.balance_back, R.id.balance_history, R.id.add_money_now})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.balance_back:
                getActivity().finish();
                break;
            case R.id.balance_history:
                start(HistoryFragment.getInstance());
                break;
            case R.id.add_money_now://点击立即充值
                if (mBalanceResponses == null || mBalanceResponses.size() == 0) {
                    XToastUtils.showShortToast("没有可充值的商品");
                } else if (isCheckedPosition == -1) {
                    XToastUtils.showShortToast("您还没有选择要充值的商品");
                } else {//选择要充值的商品后,弹选择支付窗
                    showSelectPayTypeDialog();
                }
                break;
            case R.id.iv_wx_pay://选择了微信支付
                mPayType = PayConfig.WX_PAY;
                setPayDrawable();
                break;
            case R.id.iv_ali_pay://选择了支付宝支付
                mPayType = PayConfig.ALI_PAY;
                setPayDrawable();
                break;
            case R.id.ll_not_set_ad_name://未设置地址
                start(ReceiveAddressFragment.getInstance(true));
                mAd.dismiss();
                break;
            case R.id.ll_add_name://点击跳转设置地址
                if (mBalanceResponse != null && mBalanceResponse.getAddress() != null) {
                    start(ReceiveAddressFragment.getInstance(true, mBalanceResponse.getAddress().getAddressId()));
                } else {
                    start(ReceiveAddressFragment.getInstance(true));
                }
                mAd.dismiss();
                break;
            case R.id.iv_dismiss:
                mAd.dismiss();
                break;
            case R.id.tv_pay_now://弹窗立即充值
                setPayTypeOrNot();
                break;
        }
    }

    private void setPayTypeOrNot() {
        switch (mPayType) {
            case PayConfig.WX_PAY://选择微信支付
                giveGoods();
                break;
            case PayConfig.ALI_PAY://选择支付宝支付
                giveGoods();
                break;
            default://未选择
                XToastUtils.showShortToast("请选择充值方式");
                break;
        }
    }

    /**
     * 弹出选择支付方式对话框
     */
    private void showSelectPayTypeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity, R.style.Dialog);
        View view = View.inflate(mActivity, R.layout.dialog_balance_confirm_select_pay_method, null);
        builder.setView(view);
        //创建对话框
        mAd = builder.create();
        mAd.show();
        Window dialogWindow = mAd.getWindow();
        WindowManager.LayoutParams attributes = dialogWindow.getAttributes();
        attributes.width = Utils.getScreenWidth();
        dialogWindow.setAttributes(attributes);
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialogWindow.setWindowAnimations(R.style.DialogAnimation);
        mLlSelectReceiveAddress = (LinearLayout) view.findViewById(R.id.ll_select_receive_address);
        mLlAdName = (LinearLayout) view.findViewById(R.id.ll_add_name);
        mLlNotSetAdName = (LinearLayout) view.findViewById(R.id.ll_not_set_ad_name);
        mTvAdName = (TextView) view.findViewById(R.id.tv_ad_name);
        mTvAdPhoneNum = (TextView) view.findViewById(R.id.tv_ad_phone_num);
        mTvStrAddress = (TextView) view.findViewById(R.id.tv_str_address);
        mIvDismiss = (ImageView) view.findViewById(R.id.iv_dismiss);
        mWxPay = (ImageView) view.findViewById(R.id.iv_wx_pay);
        mAliPay = (ImageView) view.findViewById(R.id.iv_ali_pay);
        mTvPayNow = (TextView) view.findViewById(R.id.tv_pay_now);
        mWxPay.setOnClickListener(this);
        mAliPay.setOnClickListener(this);
        mIvDismiss.setOnClickListener(this);
        mTvPayNow.setOnClickListener(this);
        mPayType = Utils.getLastRechargeType();
        //        if (getArguments() != null) {
        //            mPayType = getArguments().getInt(IntentConfig.PAY_TYPE);
        //            System.out.println("###########get " + mPayType);
        //
        //        }
        setPayDrawable();
        giveGoodsOrNot();
    }

    private void setPayDrawable() {
        if (mPayType == 1) {//微信支付
            mWxPay.setImageResource(R.drawable.pay_wechat_p);
            mAliPay.setImageResource(R.drawable.pay_alipay_n);
        } else if (mPayType == 2) {//支付宝支付
            mAliPay.setImageResource(R.drawable.pay_alipay_p);
            mWxPay.setImageResource(R.drawable.pay_wechat_n);
        }
    }

    //判断是否赠送商品,赠送商品显示收货地址,不赠送商品,隐藏收货地址
    private void giveGoodsOrNot() {
        mBalanceResponse = mBalanceResponses.get(isCheckedPosition);//isCheckedPosition默认为第一个0
        List<BalanceResponse.RechargeGoodsItemListBean> rechargeGoodsItemList = mBalanceResponse.getRechargeGoodsItemList();
        //如果赠送商品
        int goodsType = 0;
        if (rechargeGoodsItemList != null && rechargeGoodsItemList.size() != 0) {
            for (int i = 0; i < rechargeGoodsItemList.size(); i++) {
                int itemType = rechargeGoodsItemList.get(i).getItemType();
                if (itemType == 1) {//赠送类型为商品
                    goodsType = 1;
                }
            }
            if (goodsType == 1) {//存在赠送商品,显示收货地址
                mLlSelectReceiveAddress.setVisibility(View.VISIBLE);
                //判断是否设置过默认地址,设置过显示默认地址,未设置显示未设置
                Address address = Utils.getDefaultAddress();
                if (address == null) {//未设置过默认地址
                    mLlNotSetAdName.setVisibility(View.VISIBLE);
                    mLlNotSetAdName.setOnClickListener(this);
                    mLlAdName.setVisibility(View.GONE);
                } else {//设置过默认地址
                    mLlNotSetAdName.setVisibility(View.GONE);
                    mLlAdName.setOnClickListener(this);
                    mLlAdName.setVisibility(View.VISIBLE);
                    mBalanceResponse.setAddress(address);
                    setReceiveAddress(address);
                }
            } else {//不存在赠送商品,隐藏收货地址
                mLlSelectReceiveAddress.setVisibility(View.GONE);
            }
        } else {//不存在赠送商品,隐藏收货地址
            mLlSelectReceiveAddress.setVisibility(View.GONE);
        }
    }

    //判断是否赠送商品,赠送商品配送判断,不赠送商品,直接支付
    private void giveGoods() {
        mBalanceResponse = mBalanceResponses.get(isCheckedPosition);
        List<BalanceResponse.RechargeGoodsItemListBean> rechargeGoodsItemList = mBalanceResponse.getRechargeGoodsItemList();
        //如果赠送商品
        int goodsType = 0;
        if (rechargeGoodsItemList != null && rechargeGoodsItemList.size() != 0) {
            for (int i = 0; i < rechargeGoodsItemList.size(); i++) {
                int itemType = rechargeGoodsItemList.get(i).getItemType();
                if (itemType == 1) {//赠送类型为商品
                    goodsType = 1;
                }
            }
            if (goodsType == 1) {//存在赠送商品,配送判断
                getExpress();
            } else {//不存在赠送商品,直接支付
                gotoPay();
                mAd.dismiss();
            }
        } else {//不存在赠送商品,直接支付
            gotoPay();
            mAd.dismiss();
        }
    }

    private void setReceiveAddress(Address address) {
        if (mLlNotSetAdName.isShown()) {
            mLlNotSetAdName.setVisibility(View.GONE);
            mLlAdName.setOnClickListener(this);
            mLlAdName.setVisibility(View.VISIBLE);
        }
        mTvAdName.setText(address.getAdName());
        mTvAdPhoneNum.setText(address.getAdPhone());
        mTvStrAddress.setText(address.getStrAddress());
    }

    /**
     * 配送判断详细说明,判断地址是否在配送范围内
     */
    private void getExpress() {
        long shopId = 0;
        List<BalanceResponse.RechargeGoodsItemListBean> rechargeGoodsItemList = mBalanceResponse.getRechargeGoodsItemList();
        for (int i = 0; i < rechargeGoodsItemList.size(); i++) {
            BalanceResponse.RechargeGoodsItemListBean rechargeGoodsItemListBean = rechargeGoodsItemList.get(i);
            if (rechargeGoodsItemListBean.getItemType() == 1) {
                shopId = rechargeGoodsItemListBean.getShopId();
                break;
            }
        }
        if (mBalanceResponse.getAddress() == null) {
            //地址为空,还没有选择地址,跳到选择地址
            showAddressNotSet();
            mAd.dismiss();
            return;
        }
        OrderApi.express(mActivity, mUserLoginInfo.getUserId(), mSupplierId, mBalanceResponse.getAddress().getAddressId(), shopId, new JsonCallback<Express>(mActivity, false) {

            @Override
            public void onSuccess(Express express, Call call, Response response) {
                //在配送范围内,去支付
                gotoPay();
                mAd.dismiss();
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                //不在配送范围内
                showAddressNotExpress();
                mAd.dismiss();
            }
        });
    }

    /**
     * 未设置地址对话框
     */
    private void showAddressNotSet() {
        CommonDialog dialog = CommonDialog.createSingleButton(getString(R.string.go_sel_address), "您还没有设置收货地址");
        dialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
            }

            @Override
            public void right() {
            }

            @Override
            public void middle() {
                dialog.dismiss();
                start(ReceiveAddressFragment.getInstance(true));
                mAd.dismiss();
            }
        });
        dialog.show(getFragmentManager(), "address");
    }


    /**
     * 地址不支持配送对话框
     */
    private void showAddressNotExpress() {
        CommonDialog dialog = CommonDialog.createSingleButton(getString(R.string.go_sel_address), getString(R.string.address_not_express));
        dialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
            }

            @Override
            public void right() {
            }

            @Override
            public void middle() {
                dialog.dismiss();
                if (mBalanceResponse != null && mBalanceResponse.getAddress() != null) {
                    start(ReceiveAddressFragment.getInstance(true, mBalanceResponse.getAddress().getAddressId()));
                } else {
                    start(ReceiveAddressFragment.getInstance(true));
                }
                mAd.dismiss();
            }
        });
        dialog.show(getFragmentManager(), "address");
    }

    //进入支付
    private void gotoPay() {
        switch (mPayType) {
            case PayConfig.WX_PAY://微信支付
                //如果选择微信支付 先判断是否支付微信客户端支付 （是否支持支付版本 和 是否安装客户端）
                if (WXPayUtils.checkIsSupportWXPay(mActivity)) {
                    addOrder();
                }
                break;
            case PayConfig.ALI_PAY://支付宝
                addOrder();
                break;
        }
    }

    /**
     * 生成订单
     */
    private void addOrder() {
        BalanceResponse balanceResponse = mBalanceResponses.get(isCheckedPosition);
        long addressId;
        if (balanceResponse.getAddress() == null) {
            addressId = 0;
        } else {
            addressId = balanceResponse.getAddress().getAddressId();
        }
        AccountApi.recharge(mActivity, Utils.getUserLoginInfo().getUserId(), balanceResponse.getGoodsId(), addressId, new DialogCallback<RechargeResponse>(mActivity, getString(R.string.submitting_order)) {

            @Override
            public void onSuccess(RechargeResponse rechargeResponse, Call call, Response response) {
                EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_BALANCE_ADD_ORDER_SUCCESS));
                //订单生成成功,去支付
                XTipsDialog.showSuccess(mActivity, getString(R.string.submit_order_suc), () -> {
                    if (mPayType == PayConfig.WX_PAY) {
                        invokeWXPay(rechargeResponse, rechargeResponse.getPaymentPrice(), null);
                    } else if (mPayType == PayConfig.ALI_PAY) {
                        invokeAliPay(rechargeResponse, rechargeResponse.getPaymentPrice(), null);
                    }
                });
            }
        });
    }


    /**
     * 调用微信支付
     *
     * @param rechargeResponse 充值订单消息
     * @param paymentPrice     需付款
     * @param availableBalance 可用余额 混合支付用到
     */
    private void invokeWXPay(RechargeResponse rechargeResponse, double paymentPrice, Double availableBalance) {
        PayApi.wxpay(mActivity, rechargeResponse.getSupplierId(), rechargeResponse.getUserId(), Utils.getUserLoginInfo().getUserAlias(), 1, paymentPrice, availableBalance, rechargeResponse.getOrderId(), rechargeResponse.getOrderNo(), new DialogCallback<WXPay>(mActivity, getString(R.string.get_wxpay_info)) {
            @Override
            public void onSuccess(WXPay pay, Call call, Response response) {
                WXPayUtils.payByWX(pay);
            }
        });
    }

    /**
     * 调用支付宝支付
     *
     * @param rechargeResponse 充值订单消息
     */
    private void invokeAliPay(RechargeResponse rechargeResponse, double paymentPrice, Double availableBalance) {
        PayApi.alipay(mActivity, rechargeResponse.getSupplierId(), rechargeResponse.getUserId(), Utils.getUserLoginInfo().getUserAlias(), 1, paymentPrice, availableBalance, rechargeResponse.getOrderId(), rechargeResponse.getOrderNo(), new DialogCallback<String>(mActivity, getString(R.string.get_alipay_info)) {
            @Override
            public void onSuccess(String pay, Call call, Response response) {
                payByALi(pay);
            }
        });
    }

    /**
     * 支付宝支付
     */
    private void payByALi(String payInfo) {
        //        String payParam = payInfo;//后台返回,签名看在本地还是服务器
        AliPayUtil aliPayUtil = AliPayUtil.createInstance(mActivity, payInfo);
        aliPayUtil.setPayCallBack(new IPayCallBack() {
            @Override
            public void paySuccess() {//支付成功
                //                XTipsDialog.showSuccess(mActivity, getString(R.string.pay_success), () -> start(PaySuccessFragment.getInstance(mRechargeResponse.getOrderId())));
                EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ALI_PAY_SUCCESS));
                //保存支付方式
                putPaytype(PayConfig.ALI_PAY);
                loadAvailableBalance();
                //充值成功判断是否设置过支付密码,未支付提示设置支付密码
                ThreadPool.postOnUiDelayed(() ->
                                PayApi.hasSetPayPwd(mActivity, new DialogCallback<String>(mActivity, LeYaoGoApplication.getContext().getString(R.string.verify_pay_environment)) {
                                    @Override
                                    public void onSuccess(String o, Call call, Response response) {
                                        if (CheckUtils.equalsString(o, HttpConfig.MSG_ERROR_CODE_10046 + "")) {//未设置过支付密码
                                            // XTipsDialog.showFail(mActivity, getString(R.string.set_pay_pwd_first), () -> Utils.startActivity(mActivity, SetPwdActivity.class));
                                            showPaySuccessNotSetPwd();
                                        } else {//设置过支付密码
                                            showPaySuccess();
                                        }
                                    }
                                })
                        , 300);
            }

            @Override
            public void payFailed() {//支付失败
                XToastUtils.showShortToast(LeYaoGoApplication.getContext().getString(R.string.pay_failed));
            }

            @Override
            public void payOnWaitForConfirm() {//结果等待确认
                XToastUtils.showShortToast(LeYaoGoApplication.getContext().getString(R.string.pay_wait_to_confirm));
            }

            @Override
            public void userCanceled() {
                //                XTipsDialog.showFail(mActivity, getString(R.string.pay_cancel), () -> cancelToBalance());
                XToastUtils.showShortToast(LeYaoGoApplication.getContext().getString(R.string.pay_cancel));
            }
        });
        aliPayUtil.startToPay();
    }

    //支付成功保存支付方式
    private void putPaytype(int payType) {
        //        Bundle bundle = new Bundle();
        //        bundle.putInt(IntentConfig.PAY_TYPE, payType );
        //        BalanceFragment.getInstance().setArguments(bundle);
        //        getArguments().putInt(IntentConfig.PAY_TYPE, payType);
        //        int anInt = getArguments().getInt(IntentConfig.PAY_TYPE);
        //        System.out.println("###########put " + anInt);
        Utils.putLastRechargeType(payType);
    }

    //    //显示充值成功,还没有设置支付密码的弹框
    //    private void showPaySuccessNotSetPwd() {
    //        View view = View.inflate(mActivity, R.layout.recharge_success_dialog, null);
    //        AlertDialog dialog = Utils.showCornerDialog(mActivity, view, 236, 138);
    //        TextView sure = (TextView) dialog.findViewById(R.id.tv_dialog_sure);
    //        TextView tvCancel = (TextView) dialog.findViewById(R.id.tv_dialog_cancel);
    //        sure.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //                dialog.dismiss();
    //            }
    //        });
    //        tvCancel.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //                Utils.startActivity(mActivity, SetPwdActivity.class);
    //                dialog.dismiss();
    //            }
    //        });
    //
    //    }

    /**
     * 显示充值成功,还没有设置支付密码的弹框
     */
    private void showPaySuccessNotSetPwd() {
        CommonDialog setPwdDialog = CommonDialog.createTwoButton("稍后", "前往设置", "您还未设置支付密码,前往设置", "充值成功");
        setPwdDialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
                setPwdDialog.dismiss();
            }

            @Override
            public void right() {
                Utils.startActivity(mActivity, SetPwdActivity.class);
                setPwdDialog.dismiss();
            }

            @Override
            public void middle() {
            }
        });
        setPwdDialog.show(getFragmentManager(), "goto_set_pwd");
    }

    //    //显示充值成功弹框
    //    private void showPaySuccess() {
    //        View view = View.inflate(mActivity, R.layout.recharge_dialog, null);
    //        AlertDialog dialog = Utils.showCornerDialog(mActivity, view, 236, 138);
    //        TextView tvCancel = (TextView) dialog.findViewById(R.id.tv_dialog_cancel);
    //        tvCancel.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //                dialog.dismiss();
    //            }
    //        });
    //    }

    /**
     * 显示充值成功弹框
     */
    private void showPaySuccess() {
        CommonDialog setPwdDialog = CommonDialog.createSingleButton("完成", "充值成功");
        setPwdDialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
            }

            @Override
            public void right() {
            }

            @Override
            public void middle() {
                setPwdDialog.dismiss();
            }
        });
        setPwdDialog.show(getFragmentManager(), "goto_set_pwd");
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);

        switch (eventManager.getEventCode()) {
            case LeEventCode.MSG_CODE_MODIFY_SEL_ADDRESS:
                Address address = null;
                if (eventManager.getData() != null && eventManager.getData() instanceof Address) {
                    address = (Address) eventManager.getData();
                }
                if (address == null) {
                    return;
                }
                mAd.show();
                mBalanceResponse.setAddress(address);
                setReceiveAddress(address);
                break;

            case LeEventCode.MSG_CODE_PAY_SUCCESS://微信支付成功
                //                start(PaySuccessFragment.getInstance(mRechargeResponse.getOrderId()));
                //保存支付方式
                putPaytype(PayConfig.WX_PAY);
                //充值成功判断是否设置过支付密码,未支付提示设置支付密码
                ThreadPool.postOnUiDelayed(() ->
                                PayApi.hasSetPayPwd(mActivity, new DialogCallback<String>(mActivity, getString(R.string.verify_pay_environment)) {
                                    @Override
                                    public void onSuccess(String o, Call call, Response response) {
                                        if (CheckUtils.equalsString(o, HttpConfig.MSG_ERROR_CODE_10046 + "")) {//未设置过支付密码
                                            // XTipsDialog.showFail(mActivity, getString(R.string.set_pay_pwd_first), () -> Utils.startActivity(mActivity, SetPwdActivity.class));
                                            showPaySuccessNotSetPwd();
                                        } else {//设置过支付密码
                                            showPaySuccess();
                                        }
                                    }
                                })
                        , 300);
                loadAvailableBalance();
                break;
            case LeEventCode.MSG_CODE_RECEIVE_ADDRESS_FRAGMENT_BACK://收货地址返回
                if (!mAd.isShowing()) {
                    mAd.show();
                }
                Address defaultAddress = Utils.getDefaultAddress();
                if (defaultAddress != null) {
                    mLlNotSetAdName.setVisibility(View.GONE);
                    mLlAdName.setVisibility(View.VISIBLE);
                    mLlAdName.setOnClickListener(this);
                    mBalanceResponse.setAddress(defaultAddress);
                    setReceiveAddress(defaultAddress);
                } else {
                    mLlNotSetAdName.setVisibility(View.VISIBLE);
                    mLlAdName.setVisibility(View.GONE);
                    mLlNotSetAdName.setOnClickListener(this);
                }
                break;
        }
    }


    @Override
    public boolean isSpringMode() {
        return true;
    }
}